#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
增强版智能算法选择器

根据优化方案实现的多算法智能调度系统：
1. 算法性能评估器
2. 智能算法选择器
3. 参数自动调优
4. 性能预测模型
"""

import numpy as np
import pandas as pd
from typing import Dict, List, Any, Optional, Tuple, Callable
from dataclasses import dataclass, asdict
from enum import Enum
import time
import logging
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
import joblib
import os

try:
    from .problem_classifier import ProblemType, ProblemClassification
except ImportError:
    from problem_classifier import ProblemType, ProblemClassification


class AlgorithmCategory(Enum):
    """算法类别"""
    EXACT = "exact"  # 精确算法
    METAHEURISTIC = "metaheuristic"  # 元启发式算法
    MACHINE_LEARNING = "machine_learning"  # 机器学习算法
    HYBRID = "hybrid"  # 混合算法


class AlgorithmComplexity(Enum):
    """算法复杂度"""
    LOW = "low"  # O(n) - O(n²)
    MEDIUM = "medium"  # O(n²) - O(n³)
    HIGH = "high"  # O(2^n) 及以上


@dataclass
class AlgorithmProfile:
    """算法配置文件"""
    name: str
    category: AlgorithmCategory
    complexity: AlgorithmComplexity
    max_variables: int
    max_objectives: int
    supports_constraints: bool
    supports_integer: bool
    supports_binary: bool
    guarantee_optimal: bool
    typical_runtime: float  # 秒
    memory_requirement: str  # low, medium, high
    convergence_rate: float  # 0-1
    solution_quality: float  # 0-1
    parameter_sensitivity: float  # 0-1
    description: str
    default_parameters: Dict[str, Any]


@dataclass
class AlgorithmPerformanceMetrics:
    """算法性能指标"""
    execution_time: float
    solution_quality: float
    convergence_rate: float
    memory_usage: float
    success_rate: float
    robustness: float
    scalability: float
    overall_score: float


@dataclass
class AlgorithmRecommendation:
    """算法推荐结果"""
    primary_algorithm: str
    backup_algorithms: List[str]
    expected_performance: AlgorithmPerformanceMetrics
    recommended_parameters: Dict[str, Any]
    confidence_score: float
    reasoning: List[str]
    warnings: List[str]


class AlgorithmPerformanceEvaluator:
    """
    算法性能评估器
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        
        # 性能权重配置
        self.performance_weights = {
            'execution_time': 0.25,
            'solution_quality': 0.30,
            'convergence_rate': 0.15,
            'memory_usage': 0.10,
            'success_rate': 0.20
        }
        
        # 历史性能数据
        self.performance_history = {}
        
        # 基准测试结果
        self.benchmark_results = self._load_benchmark_data()
    
    def evaluate_algorithm(self, algorithm_name: str, problem_size: int, 
                          problem_type: ProblemType, 
                          problem_characteristics: Dict[str, Any]) -> AlgorithmPerformanceMetrics:
        """
        评估算法在特定问题上的性能
        
        Args:
            algorithm_name: 算法名称
            problem_size: 问题规模
            problem_type: 问题类型
            problem_characteristics: 问题特征
            
        Returns:
            AlgorithmPerformanceMetrics: 性能评估结果
        """
        # 基于历史数据和基准测试预测性能
        base_metrics = self._get_base_metrics(algorithm_name)
        
        # 根据问题规模调整
        size_factor = self._calculate_size_factor(algorithm_name, problem_size)
        
        # 根据问题类型调整
        type_factor = self._calculate_type_factor(algorithm_name, problem_type)
        
        # 根据问题特征调整
        characteristic_factor = self._calculate_characteristic_factor(
            algorithm_name, problem_characteristics
        )
        
        # 计算调整后的性能指标
        adjusted_metrics = AlgorithmPerformanceMetrics(
            execution_time=base_metrics.execution_time * size_factor * type_factor,
            solution_quality=base_metrics.solution_quality * type_factor * characteristic_factor,
            convergence_rate=base_metrics.convergence_rate * characteristic_factor,
            memory_usage=base_metrics.memory_usage * size_factor,
            success_rate=base_metrics.success_rate * type_factor,
            robustness=base_metrics.robustness * characteristic_factor,
            scalability=base_metrics.scalability,
            overall_score=0.0  # 将在下面计算
        )
        
        # 计算综合得分
        adjusted_metrics.overall_score = self._calculate_overall_score(adjusted_metrics)
        
        return adjusted_metrics
    
    def rank_algorithms(self, algorithms: List[str], 
                       problem_context: Dict[str, Any]) -> List[Tuple[str, float]]:
        """
        对算法进行排序
        
        Args:
            algorithms: 候选算法列表
            problem_context: 问题上下文
            
        Returns:
            List[Tuple[str, float]]: 排序后的算法及其得分
        """
        algorithm_scores = []
        
        for algorithm in algorithms:
            metrics = self.evaluate_algorithm(
                algorithm,
                problem_context.get('problem_size', 10),
                problem_context.get('problem_type', ProblemType.SINGLE_OBJECTIVE),
                problem_context.get('characteristics', {})
            )
            algorithm_scores.append((algorithm, metrics.overall_score))
        
        # 按得分降序排序
        return sorted(algorithm_scores, key=lambda x: x[1], reverse=True)
    
    def _get_base_metrics(self, algorithm_name: str) -> AlgorithmPerformanceMetrics:
        """
        获取算法基础性能指标
        """
        # 默认性能指标（实际应用中应从历史数据或基准测试中获取）
        default_metrics = {
            'exhaustive_search': AlgorithmPerformanceMetrics(
                execution_time=1.0, solution_quality=1.0, convergence_rate=1.0,
                memory_usage=0.5, success_rate=1.0, robustness=0.9, scalability=0.2, overall_score=0.0
            ),
            'genetic_algorithm': AlgorithmPerformanceMetrics(
                execution_time=0.7, solution_quality=0.85, convergence_rate=0.8,
                memory_usage=0.6, success_rate=0.9, robustness=0.8, scalability=0.9, overall_score=0.0
            ),
            'simulated_annealing': AlgorithmPerformanceMetrics(
                execution_time=0.6, solution_quality=0.8, convergence_rate=0.7,
                memory_usage=0.4, success_rate=0.85, robustness=0.75, scalability=0.8, overall_score=0.0
            ),
            'particle_swarm': AlgorithmPerformanceMetrics(
                execution_time=0.5, solution_quality=0.82, convergence_rate=0.85,
                memory_usage=0.5, success_rate=0.88, robustness=0.78, scalability=0.85, overall_score=0.0
            ),
            'nsga2': AlgorithmPerformanceMetrics(
                execution_time=0.8, solution_quality=0.9, convergence_rate=0.85,
                memory_usage=0.7, success_rate=0.92, robustness=0.85, scalability=0.8, overall_score=0.0
            ),
            'branch_and_bound': AlgorithmPerformanceMetrics(
                execution_time=0.9, solution_quality=1.0, convergence_rate=1.0,
                memory_usage=0.8, success_rate=0.95, robustness=0.9, scalability=0.4, overall_score=0.0
            )
        }
        
        return default_metrics.get(algorithm_name, default_metrics['genetic_algorithm'])
    
    def _calculate_size_factor(self, algorithm_name: str, problem_size: int) -> float:
        """
        计算问题规模影响因子
        """
        # 不同算法的规模敏感性
        size_sensitivity = {
            'exhaustive_search': 2.0,  # 指数增长
            'branch_and_bound': 1.5,   # 较快增长
            'genetic_algorithm': 1.1,  # 线性增长
            'simulated_annealing': 1.05,
            'particle_swarm': 1.08,
            'nsga2': 1.2
        }
        
        sensitivity = size_sensitivity.get(algorithm_name, 1.1)
        
        # 基于问题规模计算因子
        if problem_size <= 5:
            return 1.0
        elif problem_size <= 10:
            return sensitivity ** 0.5
        elif problem_size <= 20:
            return sensitivity ** 1.0
        else:
            return sensitivity ** 1.5
    
    def _calculate_type_factor(self, algorithm_name: str, problem_type: ProblemType) -> float:
        """
        计算问题类型影响因子
        """
        # 算法对不同问题类型的适应性
        type_adaptation = {
            'exhaustive_search': {
                ProblemType.SINGLE_OBJECTIVE: 1.0,
                ProblemType.MULTI_OBJECTIVE: 0.8,
                ProblemType.MULTI_SCENARIO: 1.0,
                ProblemType.UNCERTAINTY: 0.7
            },
            'genetic_algorithm': {
                ProblemType.SINGLE_OBJECTIVE: 0.9,
                ProblemType.MULTI_OBJECTIVE: 0.8,
                ProblemType.MULTI_SCENARIO: 0.85,
                ProblemType.UNCERTAINTY: 0.8
            },
            'nsga2': {
                ProblemType.SINGLE_OBJECTIVE: 0.8,
                ProblemType.MULTI_OBJECTIVE: 1.0,
                ProblemType.MULTI_SCENARIO: 0.9,
                ProblemType.UNCERTAINTY: 0.85
            }
        }
        
        algorithm_factors = type_adaptation.get(algorithm_name, {})
        return algorithm_factors.get(problem_type, 0.8)
    
    def _calculate_characteristic_factor(self, algorithm_name: str, 
                                       characteristics: Dict[str, Any]) -> float:
        """
        计算问题特征影响因子
        """
        factor = 1.0
        
        # 约束密度影响
        constraint_density = characteristics.get('constraint_density', 0)
        if constraint_density > 0.5:
            factor *= 0.9  # 高约束密度降低性能
        
        # 变量类型影响
        integer_ratio = characteristics.get('integer_ratio', 0)
        if integer_ratio > 0.5:
            if algorithm_name in ['genetic_algorithm', 'simulated_annealing']:
                factor *= 0.95  # 整数变量对某些算法影响较小
            else:
                factor *= 0.85
        
        # 问题复杂度影响
        complexity = characteristics.get('complexity', 'medium')
        if complexity == 'high':
            factor *= 0.9
        elif complexity == 'low':
            factor *= 1.1
        
        return factor
    
    def _calculate_overall_score(self, metrics: AlgorithmPerformanceMetrics) -> float:
        """
        计算综合得分
        """
        # 时间得分（越短越好）
        time_score = max(0, 1 - metrics.execution_time / 10)
        
        # 综合得分
        overall_score = (
            time_score * self.performance_weights['execution_time'] +
            metrics.solution_quality * self.performance_weights['solution_quality'] +
            metrics.convergence_rate * self.performance_weights['convergence_rate'] +
            (1 - metrics.memory_usage) * self.performance_weights['memory_usage'] +
            metrics.success_rate * self.performance_weights['success_rate']
        )
        
        return min(1.0, max(0.0, overall_score))
    
    def _load_benchmark_data(self) -> Dict[str, Any]:
        """
        加载基准测试数据
        """
        # 实际应用中应从文件或数据库加载
        return {}


class EnhancedAlgorithmSelector:
    """
    增强版智能算法选择器
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.performance_evaluator = AlgorithmPerformanceEvaluator()
        
        # 算法库配置
        self.algorithm_library = {
            'exact_methods': {
                'exhaustive_search': AlgorithmProfile(
                    name='exhaustive_search',
                    category=AlgorithmCategory.EXACT,
                    complexity=AlgorithmComplexity.HIGH,
                    max_variables=10,
                    max_objectives=5,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=True,
                    typical_runtime=1.0,
                    memory_requirement='medium',
                    convergence_rate=1.0,
                    solution_quality=1.0,
                    parameter_sensitivity=0.1,
                    description='穷举搜索，保证找到全局最优解',
                    default_parameters={}
                ),
                'branch_and_bound': AlgorithmProfile(
                    name='branch_and_bound',
                    category=AlgorithmCategory.EXACT,
                    complexity=AlgorithmComplexity.HIGH,
                    max_variables=50,
                    max_objectives=3,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=True,
                    typical_runtime=5.0,
                    memory_requirement='high',
                    convergence_rate=1.0,
                    solution_quality=1.0,
                    parameter_sensitivity=0.2,
                    description='分支定界法，适用于中等规模问题',
                    default_parameters={'tolerance': 1e-6}
                )
            },
            'metaheuristics': {
                'genetic_algorithm': AlgorithmProfile(
                    name='genetic_algorithm',
                    category=AlgorithmCategory.METAHEURISTIC,
                    complexity=AlgorithmComplexity.MEDIUM,
                    max_variables=1000,
                    max_objectives=10,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=False,
                    typical_runtime=10.0,
                    memory_requirement='medium',
                    convergence_rate=0.8,
                    solution_quality=0.85,
                    parameter_sensitivity=0.6,
                    description='遗传算法，适用于大规模复杂问题',
                    default_parameters={
                        'population_size': 100,
                        'generations': 200,
                        'crossover_rate': 0.8,
                        'mutation_rate': 0.1
                    }
                ),
                'simulated_annealing': AlgorithmProfile(
                    name='simulated_annealing',
                    category=AlgorithmCategory.METAHEURISTIC,
                    complexity=AlgorithmComplexity.LOW,
                    max_variables=500,
                    max_objectives=5,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=False,
                    typical_runtime=5.0,
                    memory_requirement='low',
                    convergence_rate=0.7,
                    solution_quality=0.8,
                    parameter_sensitivity=0.7,
                    description='模拟退火算法，内存占用低',
                    default_parameters={
                        'initial_temperature': 1000,
                        'cooling_rate': 0.95,
                        'min_temperature': 0.01
                    }
                ),
                'particle_swarm': AlgorithmProfile(
                    name='particle_swarm',
                    category=AlgorithmCategory.METAHEURISTIC,
                    complexity=AlgorithmComplexity.MEDIUM,
                    max_variables=800,
                    max_objectives=8,
                    supports_constraints=True,
                    supports_integer=False,
                    supports_binary=False,
                    guarantee_optimal=False,
                    typical_runtime=8.0,
                    memory_requirement='medium',
                    convergence_rate=0.85,
                    solution_quality=0.82,
                    parameter_sensitivity=0.5,
                    description='粒子群算法，适用于连续优化',
                    default_parameters={
                        'swarm_size': 50,
                        'iterations': 300,
                        'w': 0.7,
                        'c1': 1.5,
                        'c2': 1.5
                    }
                ),
                'nsga2': AlgorithmProfile(
                    name='nsga2',
                    category=AlgorithmCategory.METAHEURISTIC,
                    complexity=AlgorithmComplexity.MEDIUM,
                    max_variables=500,
                    max_objectives=20,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=False,
                    typical_runtime=15.0,
                    memory_requirement='high',
                    convergence_rate=0.85,
                    solution_quality=0.9,
                    parameter_sensitivity=0.4,
                    description='NSGA-II算法，专门用于多目标优化',
                    default_parameters={
                        'population_size': 100,
                        'generations': 250,
                        'crossover_rate': 0.9,
                        'mutation_rate': 0.1
                    }
                )
            },
            'machine_learning': {
                'reinforcement_learning': AlgorithmProfile(
                    name='reinforcement_learning',
                    category=AlgorithmCategory.MACHINE_LEARNING,
                    complexity=AlgorithmComplexity.HIGH,
                    max_variables=200,
                    max_objectives=5,
                    supports_constraints=True,
                    supports_integer=True,
                    supports_binary=True,
                    guarantee_optimal=False,
                    typical_runtime=30.0,
                    memory_requirement='high',
                    convergence_rate=0.75,
                    solution_quality=0.85,
                    parameter_sensitivity=0.8,
                    description='强化学习算法，适用于动态决策',
                    default_parameters={
                        'learning_rate': 0.01,
                        'episodes': 1000,
                        'epsilon': 0.1
                    }
                )
            }
        }
        
        # 选择策略配置
        self.selection_strategies = {
            'performance_first': {'weight_performance': 0.7, 'weight_reliability': 0.3},
            'reliability_first': {'weight_performance': 0.3, 'weight_reliability': 0.7},
            'balanced': {'weight_performance': 0.5, 'weight_reliability': 0.5},
            'speed_first': {'weight_time': 0.8, 'weight_quality': 0.2}
        }
    
    def select_optimal_algorithm(self, problem_context: Dict[str, Any], 
                               strategy: str = 'balanced') -> AlgorithmRecommendation:
        """
        选择最优算法
        
        Args:
            problem_context: 问题上下文
            strategy: 选择策略
            
        Returns:
            AlgorithmRecommendation: 算法推荐结果
        """
        # 提取问题特征
        problem_size = problem_context.get('variable_count', 10)
        problem_type = problem_context.get('problem_type', ProblemType.SINGLE_OBJECTIVE)
        time_limit = problem_context.get('time_limit', 300)
        quality_requirement = problem_context.get('quality_requirement', 0.8)
        
        # 筛选可用算法
        candidate_algorithms = self._filter_algorithms(problem_context)
        
        # 评估算法性能
        algorithm_evaluations = {}
        for algorithm_name in candidate_algorithms:
            metrics = self.performance_evaluator.evaluate_algorithm(
                algorithm_name, problem_size, problem_type, problem_context
            )
            algorithm_evaluations[algorithm_name] = metrics
        
        # 根据策略选择算法
        selected_algorithms = self._apply_selection_strategy(
            algorithm_evaluations, strategy, problem_context
        )
        
        # 生成推荐结果
        primary_algorithm = selected_algorithms[0][0]
        backup_algorithms = [alg[0] for alg in selected_algorithms[1:3]]
        
        # 参数推荐
        recommended_parameters = self._recommend_parameters(
            primary_algorithm, problem_context
        )
        
        # 生成推理说明
        reasoning = self._generate_reasoning(
            primary_algorithm, problem_context, algorithm_evaluations[primary_algorithm]
        )
        
        # 生成警告
        warnings = self._generate_warnings(
            primary_algorithm, problem_context, algorithm_evaluations[primary_algorithm]
        )
        
        return AlgorithmRecommendation(
            primary_algorithm=primary_algorithm,
            backup_algorithms=backup_algorithms,
            expected_performance=algorithm_evaluations[primary_algorithm],
            recommended_parameters=recommended_parameters,
            confidence_score=selected_algorithms[0][1],
            reasoning=reasoning,
            warnings=warnings
        )
    
    def _filter_algorithms(self, problem_context: Dict[str, Any]) -> List[str]:
        """
        筛选可用算法
        """
        candidate_algorithms = []
        
        problem_size = problem_context.get('variable_count', 10)
        has_integer = problem_context.get('has_integer_variables', False)
        has_binary = problem_context.get('has_binary_variables', False)
        num_objectives = problem_context.get('objective_count', 1)
        
        for category, algorithms in self.algorithm_library.items():
            for name, profile in algorithms.items():
                # 检查变量数量限制
                if problem_size > profile.max_variables:
                    continue
                
                # 检查目标数量限制
                if num_objectives > profile.max_objectives:
                    continue
                
                # 检查变量类型支持
                if has_integer and not profile.supports_integer:
                    continue
                if has_binary and not profile.supports_binary:
                    continue
                
                candidate_algorithms.append(name)
        
        return candidate_algorithms
    
    def _apply_selection_strategy(self, evaluations: Dict[str, AlgorithmPerformanceMetrics],
                                strategy: str, problem_context: Dict[str, Any]) -> List[Tuple[str, float]]:
        """
        应用选择策略
        """
        strategy_config = self.selection_strategies.get(strategy, self.selection_strategies['balanced'])
        
        algorithm_scores = []
        
        for algorithm_name, metrics in evaluations.items():
            if strategy == 'performance_first':
                score = (
                    metrics.overall_score * strategy_config['weight_performance'] +
                    metrics.success_rate * strategy_config['weight_reliability']
                )
            elif strategy == 'reliability_first':
                score = (
                    metrics.success_rate * strategy_config['weight_reliability'] +
                    metrics.overall_score * strategy_config['weight_performance']
                )
            elif strategy == 'speed_first':
                time_score = max(0, 1 - metrics.execution_time / 60)  # 归一化到60秒
                score = (
                    time_score * strategy_config['weight_time'] +
                    metrics.solution_quality * strategy_config['weight_quality']
                )
            else:  # balanced
                score = (
                    metrics.overall_score * strategy_config['weight_performance'] +
                    metrics.success_rate * strategy_config['weight_reliability']
                )
            
            algorithm_scores.append((algorithm_name, score))
        
        return sorted(algorithm_scores, key=lambda x: x[1], reverse=True)
    
    def _recommend_parameters(self, algorithm_name: str, 
                            problem_context: Dict[str, Any]) -> Dict[str, Any]:
        """
        推荐算法参数
        """
        # 获取默认参数
        algorithm_profile = self._get_algorithm_profile(algorithm_name)
        if not algorithm_profile:
            return {}
        
        parameters = algorithm_profile.default_parameters.copy()
        
        # 根据问题特征调整参数
        problem_size = problem_context.get('variable_count', 10)
        
        if algorithm_name == 'genetic_algorithm':
            # 根据问题规模调整种群大小
            if problem_size > 50:
                parameters['population_size'] = min(200, problem_size * 2)
                parameters['generations'] = max(300, problem_size * 5)
            elif problem_size < 10:
                parameters['population_size'] = max(50, problem_size * 5)
                parameters['generations'] = max(100, problem_size * 10)
        
        elif algorithm_name == 'simulated_annealing':
            # 根据问题复杂度调整温度参数
            complexity = problem_context.get('complexity', 'medium')
            if complexity == 'high':
                parameters['initial_temperature'] = 2000
                parameters['cooling_rate'] = 0.98
            elif complexity == 'low':
                parameters['initial_temperature'] = 500
                parameters['cooling_rate'] = 0.9
        
        return parameters
    
    def _generate_reasoning(self, algorithm_name: str, problem_context: Dict[str, Any],
                          metrics: AlgorithmPerformanceMetrics) -> List[str]:
        """
        生成推理说明
        """
        reasoning = []
        
        algorithm_profile = self._get_algorithm_profile(algorithm_name)
        if algorithm_profile:
            reasoning.append(f"选择{algorithm_profile.description}")
        
        problem_size = problem_context.get('variable_count', 10)
        if problem_size <= 10 and algorithm_profile and algorithm_profile.guarantee_optimal:
            reasoning.append("问题规模较小，选择精确算法保证最优解")
        elif problem_size > 50:
            reasoning.append("问题规模较大，选择启发式算法平衡效率和质量")
        
        if metrics.solution_quality > 0.9:
            reasoning.append("预期解质量较高")
        
        if metrics.execution_time < 10:
            reasoning.append("预期执行时间较短")
        
        return reasoning
    
    def _generate_warnings(self, algorithm_name: str, problem_context: Dict[str, Any],
                         metrics: AlgorithmPerformanceMetrics) -> List[str]:
        """
        生成警告信息
        """
        warnings = []
        
        algorithm_profile = self._get_algorithm_profile(algorithm_name)
        
        if metrics.execution_time > 60:
            warnings.append("预期执行时间较长，建议考虑时间限制")
        
        if metrics.solution_quality < 0.7:
            warnings.append("预期解质量可能不够理想，建议调整参数或尝试其他算法")
        
        if algorithm_profile and algorithm_profile.parameter_sensitivity > 0.7:
            warnings.append("该算法对参数较敏感，建议仔细调优参数")
        
        problem_size = problem_context.get('variable_count', 10)
        if algorithm_profile and problem_size > algorithm_profile.max_variables * 0.8:
            warnings.append("问题规模接近算法上限，可能影响性能")
        
        return warnings
    
    def _get_algorithm_profile(self, algorithm_name: str) -> Optional[AlgorithmProfile]:
        """
        获取算法配置文件
        """
        for category, algorithms in self.algorithm_library.items():
            if algorithm_name in algorithms:
                return algorithms[algorithm_name]
        return None
    
    def get_algorithm_library_info(self) -> Dict[str, Any]:
        """
        获取算法库信息
        """
        info = {
            'total_algorithms': 0,
            'categories': {},
            'algorithms': {}
        }
        
        for category, algorithms in self.algorithm_library.items():
            info['categories'][category] = len(algorithms)
            info['total_algorithms'] += len(algorithms)
            
            for name, profile in algorithms.items():
                info['algorithms'][name] = {
                    'category': profile.category.value,
                    'complexity': profile.complexity.value,
                    'max_variables': profile.max_variables,
                    'guarantee_optimal': profile.guarantee_optimal,
                    'description': profile.description
                }
        
        return info


def create_enhanced_algorithm_selector() -> EnhancedAlgorithmSelector:
    """
    创建增强版算法选择器实例
    """
    return EnhancedAlgorithmSelector()